//
//  ChangePhoneView.swift
//  CMB250716
//
//  Created by Andy Lau on 16/7/25.
//

import SwiftUI

struct ChangePhoneView: View {
    @EnvironmentObject var dataManager: DataManager
    @Environment(\.dismiss) private var dismiss
    
    @State private var newPhoneNumber = ""
    @State private var oldPhoneCode = ""
    @State private var newPhoneCode = ""
    @State private var step = 1 // 1: 输入新手机号, 2: 验证旧手机, 3: 验证新手机
    @State private var showingAlert = false
    @State private var alertMessage = ""
    @State private var isLoading = false
    @State private var countdown = 60
    @State private var canResendCode = true
    @State private var timer: Timer?
    
    var body: some View {
        NavigationView {
            ZStack {
                Color(.systemGroupedBackground)
                    .ignoresSafeArea()
                
                ScrollView {
                    VStack(spacing: 24) {
                        // 进度指示器
                        HStack {
                            ForEach(1...3, id: \.self) { stepNumber in
                                Circle()
                                    .fill(stepNumber <= step ? Color.orange : Color.gray.opacity(0.3))
                                    .frame(width: 12, height: 12)
                                
                                if stepNumber < 3 {
                                    Rectangle()
                                        .fill(stepNumber < step ? Color.orange : Color.gray.opacity(0.3))
                                        .frame(height: 2)
                                }
                            }
                        }
                        .padding(.horizontal, 40)
                        .padding(.top, 20)
                        
                        // 步骤内容
                        VStack(spacing: 20) {
                            switch step {
                            case 1:
                                step1View
                            case 2:
                                step2View
                            case 3:
                                step3View
                            default:
                                EmptyView()
                            }
                        }
                        .padding(.horizontal, 20)
                    }
                }
            }
            .navigationTitle("更换手机号")
            .navigationBarTitleDisplayMode(.inline)
            .toolbar {
                ToolbarItem(placement: .navigationBarLeading) {
                    Button("取消") {
                        dismiss()
                    }
                }
            }
        }
        .alert("提示", isPresented: $showingAlert) {
            Button("确定", role: .cancel) { }
        } message: {
            Text(alertMessage)
        }
        .onDisappear {
            timer?.invalidate()
        }
    }
    
    // MARK: - 步骤1: 输入新手机号
    private var step1View: some View {
        VStack(spacing: 20) {
            VStack(alignment: .leading, spacing: 8) {
                Text("当前手机号")
                    .font(.subheadline)
                    .foregroundColor(.secondary)
                
                Text(dataManager.currentUser?.phoneNumber ?? "")
                    .font(.title2)
                    .fontWeight(.medium)
            }
            .frame(maxWidth: .infinity, alignment: .leading)
            
            VStack(alignment: .leading, spacing: 8) {
                Text("新手机号")
                    .font(.subheadline)
                    .foregroundColor(.secondary)
                
                HStack {
                    Text("+65")
                        .font(.body)
                        .foregroundColor(.primary)
                    
                    TextField("请输入新手机号", text: $newPhoneNumber)
                        #if canImport(UIKit)
                        .keyboardType(.phonePad)
                        #endif
                        .textFieldStyle(RoundedBorderTextFieldStyle())
                }
            }
            
            Text("更换手机号后，您的积分、等级和历史订单等信息将保持不变。")
                .font(.caption)
                .foregroundColor(.secondary)
                .multilineTextAlignment(.center)
            
            Button(action: {
                validateAndProceedToStep2()
            }) {
                Text("下一步")
                    .font(.headline)
                    .foregroundColor(.white)
                    .frame(maxWidth: .infinity)
                    .padding()
                    .background(newPhoneNumber.count >= 8 ? Color.orange : Color.gray)
                    .cornerRadius(10)
            }
            .disabled(newPhoneNumber.count < 8 || isLoading)
        }
        .padding(20)
        .background(Color(.systemBackground))
        .cornerRadius(12)
    }
    
    // MARK: - 步骤2: 验证旧手机号
    private var step2View: some View {
        VStack(spacing: 20) {
            VStack(alignment: .leading, spacing: 8) {
                Text("验证当前手机号")
                    .font(.headline)
                
                Text("我们已向您的当前手机号 \(dataManager.currentUser?.phoneNumber ?? "") 发送验证码")
                    .font(.subheadline)
                    .foregroundColor(.secondary)
            }
            .frame(maxWidth: .infinity, alignment: .leading)
            
            VStack(alignment: .leading, spacing: 8) {
                Text("验证码")
                    .font(.subheadline)
                    .foregroundColor(.secondary)
                
                TextField("请输入6位验证码", text: $oldPhoneCode)
                    #if canImport(UIKit)
                    .keyboardType(.numberPad)
                    #endif
                    .textFieldStyle(RoundedBorderTextFieldStyle())
                    .onChange(of: oldPhoneCode) { newValue in
                        if newValue.count > 6 {
                            oldPhoneCode = String(newValue.prefix(6))
                        }
                    }
            }
            
            HStack {
                Button(action: {
                    resendOldPhoneCode()
                }) {
                    Text(canResendCode ? "重新发送" : "重新发送(\(countdown))")
                        .font(.subheadline)
                        .foregroundColor(canResendCode ? .orange : .gray)
                }
                .disabled(!canResendCode)
                
                Spacer()
            }
            
            Button(action: {
                validateOldPhoneAndProceed()
            }) {
                Text("验证并继续")
                    .font(.headline)
                    .foregroundColor(.white)
                    .frame(maxWidth: .infinity)
                    .padding()
                    .background(oldPhoneCode.count == 6 ? Color.orange : Color.gray)
                    .cornerRadius(10)
            }
            .disabled(oldPhoneCode.count != 6 || isLoading)
        }
        .padding(20)
        .background(Color(.systemBackground))
        .cornerRadius(12)
    }
    
    // MARK: - 步骤3: 验证新手机号
    private var step3View: some View {
        VStack(spacing: 20) {
            VStack(alignment: .leading, spacing: 8) {
                Text("验证新手机号")
                    .font(.headline)
                
                Text("我们已向您的新手机号 +65\(newPhoneNumber) 发送验证码")
                    .font(.subheadline)
                    .foregroundColor(.secondary)
            }
            .frame(maxWidth: .infinity, alignment: .leading)
            
            VStack(alignment: .leading, spacing: 8) {
                Text("验证码")
                    .font(.subheadline)
                    .foregroundColor(.secondary)
                
                TextField("请输入6位验证码", text: $newPhoneCode)
                    #if canImport(UIKit)
                    .keyboardType(.numberPad)
                    #endif
                    .textFieldStyle(RoundedBorderTextFieldStyle())
                    .onChange(of: newPhoneCode) { newValue in
                        if newValue.count > 6 {
                            newPhoneCode = String(newValue.prefix(6))
                        }
                    }
            }
            
            HStack {
                Button(action: {
                    resendNewPhoneCode()
                }) {
                    Text(canResendCode ? "重新发送" : "重新发送(\(countdown))")
                        .font(.subheadline)
                        .foregroundColor(canResendCode ? .orange : .gray)
                }
                .disabled(!canResendCode)
                
                Spacer()
            }
            
            Button(action: {
                completePhoneChange()
            }) {
                Text(isLoading ? "处理中..." : "完成更换")
                    .font(.headline)
                    .foregroundColor(.white)
                    .frame(maxWidth: .infinity)
                    .padding()
                    .background(newPhoneCode.count == 6 && !isLoading ? Color.orange : Color.gray)
                    .cornerRadius(10)
            }
            .disabled(newPhoneCode.count != 6 || isLoading)
        }
        .padding(20)
        .background(Color(.systemBackground))
        .cornerRadius(12)
    }
    
    // MARK: - 方法
    private func validateAndProceedToStep2() {
        let canChange = dataManager.canChangePhone()
        guard canChange.canChange else {
            alertMessage = canChange.reason ?? "无法更换手机号"
            showingAlert = true
            return
        }
        
        // 验证新手机号格式：8位数字且以8或9开头
        guard newPhoneNumber.count == 8,
              newPhoneNumber.allSatisfy({ $0.isNumber }),
              newPhoneNumber.first == "8" || newPhoneNumber.first == "9" else {
            alertMessage = "请输入正确的电话号码"
            showingAlert = true
            return
        }
        
        guard newPhoneNumber != dataManager.currentUser?.phoneNumber else {
            alertMessage = "新手机号不能与当前手机号相同"
            showingAlert = true
            return
        }
        
        // 发送验证码到旧手机
        let oldPhone = dataManager.currentUser?.phoneNumber ?? ""
        let verificationType = VerificationType.phoneChange(oldPhone: oldPhone, newPhone: newPhoneNumber)
        let _ = dataManager.sendVerificationCode(for: verificationType)
        
        step = 2
        startCountdown()
    }
    
    private func validateOldPhoneAndProceed() {
        let oldPhone = dataManager.currentUser?.phoneNumber ?? ""
        let verificationType = VerificationType.phoneChange(oldPhone: oldPhone, newPhone: newPhoneNumber)
        
        guard dataManager.verifyCode(oldPhoneCode, for: verificationType) else {
            alertMessage = "验证码错误，请重新输入"
            showingAlert = true
            return
        }
        
        // 发送验证码到新手机
        let _ = dataManager.sendVerificationCode(for: verificationType)
        
        step = 3
        startCountdown()
    }
    
    private func completePhoneChange() {
        isLoading = true
        
        let success = dataManager.changePhoneNumber(
            newPhone: newPhoneNumber,
            oldPhoneCode: oldPhoneCode,
            newPhoneCode: newPhoneCode
        )
        
        isLoading = false
        
        if success {
            alertMessage = "手机号更换成功！"
            showingAlert = true
            DispatchQueue.main.asyncAfter(deadline: .now() + 1.5) {
                dismiss()
            }
        } else {
            alertMessage = "更换失败，请检查验证码是否正确"
            showingAlert = true
        }
    }
    
    private func resendOldPhoneCode() {
        let oldPhone = dataManager.currentUser?.phoneNumber ?? ""
        let verificationType = VerificationType.phoneChange(oldPhone: oldPhone, newPhone: newPhoneNumber)
        let _ = dataManager.sendVerificationCode(for: verificationType)
        startCountdown()
    }
    
    private func resendNewPhoneCode() {
        let oldPhone = dataManager.currentUser?.phoneNumber ?? ""
        let verificationType = VerificationType.phoneChange(oldPhone: oldPhone, newPhone: newPhoneNumber)
        let _ = dataManager.sendVerificationCode(for: verificationType)
        startCountdown()
    }
    
    private func startCountdown() {
        canResendCode = false
        countdown = 60
        
        timer?.invalidate()
        timer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { _ in
            countdown -= 1
            if countdown <= 0 {
                canResendCode = true
                timer?.invalidate()
            }
        }
    }
}

#Preview {
    ChangePhoneView()
        .environmentObject(DataManager.shared)
}